package com.ybwh.springboot1.controller;

import com.ybwh.springboot1.util.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ybwh.springboot1.common.RespData;
import com.ybwh.springboot1.service.UserService;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * 登录模块控制器
 */
@Slf4j
@Controller
@RequestMapping("/")
public class LoginController {

	@Autowired
	private UserService userService;

	/**
	 * 登录页面
	 *
	 * @return
	 */
	@RequestMapping("/login")
	public ModelAndView login() {
		ModelAndView mav = new ModelAndView("/login");
		return mav;
	}

	/**
	 * 登录动作
	 *
	 * @param username 用户名
	 * @param password 密码
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/doLogin")
	public RespData<String> doLogin(@RequestParam("username") String username,
			@RequestParam("password") String password, HttpServletResponse response) {
		if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
			return RespData.failedResp("用户名或密码不能为空！");
		}

		try {
			RespData<String> resp = userService.doLogin(username, password);

			if (Objects.equals(RespData.SUCCEED_CODE, resp.getCode())) {
				TokenUtil.setToken(response, resp.getData());
			}

			return resp;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("login msg!!", e);
			return RespData.failedResp(ExceptionUtils.getStackTrace(e));
		}

	}

	/**
	 * 退出登录
	 *
	 * @return
	 */
	@RequestMapping("/loginOut")
	public ModelAndView loginOut(HttpServletResponse response) {
		ModelAndView mav = new ModelAndView("/login");
		TokenUtil.setToken(response, "");
		return mav;
	}
	
	
	
	/**
	 * 个人信息
	 */
	@RequestMapping("/selfInfo")
	public ModelAndView selfInfo() {
		ModelAndView mav = new ModelAndView("/selfInfo");
		return mav;
	}

}
